// subPages/pages/order/breakfast/breakfast.js
var app = getApp();
var request = app.request;
import LoadMore from '../../../utils/LoadMore.js';
const load = new LoadMore;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBar: app.globalData.statusBar,
    url: app.globalData.setting.url,
    userInfo: null,
    isOrder: false,
    recommend: [],
    secCategories: [],
    subCategoryId: 1,
    goodListHeight: 550,
    openSpecModal: false, //是否打开规格弹窗
    currentPage: 1,
    goodsInputNum: 1,
    goods: [],
    datas: [],
    openSpecModal: false, //是否打开规格弹窗
    goodsInputNum: 1, //选中的商品件数
    specSelect: 0, //选中的组合规格数组spec_goods_price下标
    optionItemId: 0, //页面参数，页面初始化指定显示的itemid，用于活动
    shippingCost: 0,
    hasSpec: true,
    select: { //选择的(规格)商品的参数，用于显示
      price: 0,
      stock: 0,
      specName: '',
      activity: null
    },
    isBragain: false,
    isSeparate: true,
    indexnum: 0,
    openFilterModal: false,
    min: "", //最低价
    max: "", //最高价
    oldGoods: [], // 旧数据
    secCategories: [],
    secCategoryId: null,
    point_use_percent: 0,
    cartGoodsNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo
      });
    }, true);
    load.init(this, '', 'recommend');
    that.requestCategories(1);
    that.requestRecommend();
  },

  onShow() {
    this.getGoods(this.data.subCategoryId, 1);
    this.requestCardNum();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.data.recommend = [];
    this.data.currentPage = 1;
    this.requestRecommend();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (load.canloadMore() && !this.data.isOrder) {
      this.data.currentPage++;
      this.requestRecommend('more');
    }
  },

  changeOrder() {
    this.setData({
      isOrder: true
    })
  },

  // 商品列表
  requestRecommend: function (type) {
    let that = this;
    let requestUrl = '/api/index/getHotGood?page=' + that.data.currentPage;
    load.request(requestUrl, function (res) {
      wx.stopPullDownRefresh();
      var list = res.data.result;
      for (var i = 0; i < list.length; i++) {
        list[i]['discount'] = Math.round(list[i].shop_price / list[i].market_price * 100) / 10;
      }
      console.log(that.data.recommend)
      // that.setData({
      //   recommend: list
      // });
      if (type == 'more') {
        let result = res.data.result || [];
        console.log(result)
        console.log([...that.data.recommend, ...result])
        // that.setData({
        // 	recommend: [...that.data.recommend, ...result]
        // })
      }
      console.log(that.data.recommend)
    });
  },

  getGoods(id, pid) {
    var that = this;
    request.get('/api/goods/getGoods', {
      data: {
        'pid': pid,
        'id': id,
        'sale': 0,
        'price': 0
      },
      success: function (res) {
        var list = res.data.result;
        for (var i = 0; i < list.length; i++) {
          list[i]['discount'] = Math.round(list[i].shop_price / list[i].market_price * 100) / 10;
        }
        that.setData({
          goods: res.data.result,
          oldGoods: res.data.result,
          min: "",
          max: ""
        });
      }
    });
  },

  toDetail: function (e) {
    console.log(e.currentTarget.dataset.item);
    let {
      goods_id
    } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/subPages/pages/order/breakfastDetail/breakfastDetail?goods_id=${goods_id}`,
    })
  },

  toTeamOrder() {
    wx.navigateTo({
      url: '/subPages/pages/order/team_order/team_order',
    })
  },

  //请求分类
  requestCategories: function (parenId) {
    var that = this;
    request.get('/api/goods/goodsSecAndThirdCategoryList', {
      data: {
        'parent_id': parenId
      },
      success: function (res) {
        var list = res.data.result;
        that.getGoods(0, parenId);
        that.setData({
          secCategories: list,
          currentCategoryId: parenId
        });
      }
    });
  },

  switchSecondCategory: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      subCategoryId: id
    })
    // that.requestCategories(id);
    that.getGoods(id, 1);
  },

  clickMenu(e) {
    let that = this;
    //在个人中心浏览其他入口页面前判断是否登录
    if (!that.data.userInfo) {
      app.getUserInfo(function (userInfo) {
        that.setData({
          userInfo: userInfo
        });
      }, true, false);
      return false;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    });
  },

  back() {
    if (this.data.isOrder) {
      this.setData({
        isOrder: false
      })
    } else {
      wx.navigateBack();
    }
  },
  /** 关闭规格弹窗 */
  closeSpecModal: function () {
    this.setData({
      openSpecModal: false
    });
  },
  /** 打开规格弹窗 */
  openSpecModel: function (e) {
    var that = this;
    request.get('/api/goods/goodsInfo', {
      data: {
        id: e.currentTarget.dataset.goods_id
      },
      failRollback: true,
      success: function (res) {
        that.setData({
          data: res.data.result,
          openSpecModal: true,
          goodsInputNum: 1
        });
        that.initData(res.data.result);
      }
    });
  },
  /** 初始化数据，注意顺序 */
  initData: function (data) {
    //检查商品
    this.initCheckGoods(data);
    //检查一下购物的数量，可能无库存
    this.checkCartNum(this.data.goodsInputNum);
  },
  /** 检查商品 */
  initCheckGoods: function (data) {
    var that = this;
    request.post('/api/goods/activity', {
      data: {
        goods_id: data.goods.goods_id,
        item_id: data.goods.spec_goods_price.length > 0 ? data.goods.spec_goods_price[0]['item_id'] : '',
      },
      success: function (res) {
        //初始化规格
        if (res.data.result.goods.activity_is_on == 1) {
          that.initSpecsPrice(res.data.result);
        } else {
          data.goods.prom_type = 0;
          that.initSpecsPrice(data);
        }
      }
    });
  },
  /** 初始化所有规格 */
  initSpecsPrice: function (data) {
    var specSelect = 0; //初始化选中第一个规格 
    var specs = this.data.data.goods.spec_goods_price;
    if (specs.length == 0) {
      //没有规格
      this.initActivity(data.goods);
      return;
    }
    this.initSelectSpecGoods();
  },
  /** 初始化选中的规格商品 */
  initSelectSpecGoods: function () {
    var specSelect = this.data.specSelect;
    var specs = this.data.data.goods.spec_goods_price;
    var itemId = specs[specSelect].item_id;
    if (specs[specSelect].prom_type == 0) {
      var noActivity = {
        prom_type: 0
      };
      specs[specSelect].activity = noActivity;
      this.initActivity(noActivity);
    } else if (typeof specs[specSelect].activity != 'undefined') {
      this.initActivity(specs[specSelect].activity);
    } else {
      this.requestSpecInfo(specSelect);
    }
  },
  /** 点击规格按钮的回调函数 */
  selectSpec: function (e) {
    //对商品数量进行判断，对库存进行判断
    var itemId = e.currentTarget.dataset.itemid;
    var listIdx = e.currentTarget.dataset.listidx;
    var list = this.data.data.goods_spec_list;
    if (list[listIdx].selectItemId == itemId) {
      return;
    }
    list[listIdx].selectItemId = itemId;
    var newSpecKeys = [];
    for (var i = 0; i < list.length; i++) {
      newSpecKeys[i] = list[i].selectItemId;
    }
    //item排序,生成key
    var newSpecKeys = util.sortSize(newSpecKeys).join('_');
    var newSpecSelect = 0;
    var specs = this.data.data.goods.spec_goods_price;
    var hasSpec = false;
    for (var i = 0; i < specs.length; i++) {
      if (specs[i].key == newSpecKeys) {
        hasSpec = true;
        newSpecSelect = i;
        break;
      }
    }
    this.setData({
      hasSpec: hasSpec,
      specSelect: newSpecSelect,
      'data.goods_spec_list': list,
      isBragain: this.data.isSeparate ? false : true,
    });
    this.initSelectSpecGoods();
    this.checkCartNum(this.data.goodsInputNum);
  },
  /** 初始化显示的活动信息 */
  initActivity: function (activity) {
    if (activity.prom_type && activity.prom_type != 6) {
      var startTime = (new Date()).getTime();
      if (activity.prom_type == 1) { //抢购
        activity.priceName = '抢购价';
        activity.countName = '限时抢购';
      } else if (activity.prom_type == 2) { //团购
        activity.priceName = '团购价';
        activity.countName = '限时团购';
      } else if (activity.prom_type == 3) { //促销
        activity.countName = '优惠促销';
      } else if (activity.prom_type == 4) { //预售
        activity.priceName = '预售价';
        activity.countName = '预售商品';
      } else if (activity.prom_type == 8) { //砍价
        !this.data.isBragain ? activity.priceName = '砍价享' : activity.priceName = '';
        !this.data.isBragain ? activity.countName = '砍价活动' : activity.countName = '';
      }
      activity.countTime = '--天--时--分--秒';
      if (!activity.diffTime) {
        activity.diffTime = (new Date()).getTime() - activity.server_current_time * 1000;
      }
    } else if (activity.prom_type == 6) {
      activity.countName = '该商品正在参与拼团';
      activity.goods_id = activity.goods_id;
      activity.team_id = activity.prom_id ? activity.prom_id : 0;
      activity.item_id = activity.item_id ? activity.item_id : 0;
    }
    this.setData({
      'select.activity': activity
    });
    this.destroyActivityTimer();
    this.createActivityTimer();
    this.initSelectedData();
  },

  /** 初始化选中的（规格）商品的显示参数 */
  initSelectedData: function () {
    var goods = this.data.data.goods;
    var activity = this.data.select.activity;
    var specs = this.data.data.goods.spec_goods_price;
    var specSelect = this.data.specSelect;
    var stock = 0;
    var price = 0;
    if (activity.prom_type == 1 || activity.prom_type == 2) {
      price = activity.shop_price;
      stock = activity.store_count;
    } else if (activity.prom_type == 3) {
      price = activity.shop_price;
      // stock = specs.length > 0 ? specs[specSelect].store_count : goods.store_count;
      stock = activity.store_count;
    } else if (activity.prom_type == 4) {
      price = activity.shop_price;
      //stock = specs.length > 0 ? specs[specSelect].store_count : goods.store_count;
      stock = activity.store_count;
    } else if (activity.prom_type == 8 && !this.data.isBragain) {
      price = activity.end_price ? activity.end_price : activity.shop_price;
      stock = activity.store_count;
      this.setData({
        'select.bargain_price': price,
      });
    } else if (specs.length > 0) {
      price = specs[specSelect].price;
      stock = specs[specSelect].store_count;
    } else {
      price = goods.shop_price;
      stock = goods.store_count;
    }
    this.setData({
      'select.price': price,
      'select.stock': stock,
      'select.specName': specs.length > 0 ? specs[specSelect].key_name : '',
    });
    if (this.data.isBragain) {
      this.setData({
        isBragain: false
      })
    }
  },
  /** 检查是否倒计时是否结束 */
  checkActivityTime: function () {
    var that = this;
    var activity = that.data.select.activity;
    var remainTime = activity.end_time * 1000 - (new Date()).getTime() + activity.diffTime;
    if (remainTime > 0) {
      remainTime = util.remainTime(remainTime);
      that.setData({
        'select.activity.countTime': remainTime
      });
    } else {
      that.requestSpecInfo(that.data.specSelect);
      return;
    }
  },

  /** 创建活动倒计时定时器 */
  createActivityTimer: function () {
    var that = this;
    var activity = that.data.select.activity;
    if (!activity.prom_type || activity.prom_type == 6 || that.data.isBragain) {
      return;
    }
    that.data.timer = setInterval(function () {
      that.checkActivityTime();
    }, 1000);
  },

  /** 销毁活动倒计时定时器 */
  destroyActivityTimer: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },
  /** 请求规格商品的活动信息 */
  requestSpecInfo: function (specSelect) {
    var that = this;
    var specs = that.data.data.goods.spec_goods_price;
    request.get('/api/goods/activity', {
      data: {
        goods_id: that.data.data.goods.goods_id,
        item_id: specs.length > 0 ? specs[specSelect].item_id : '',
      },
      success: function (res) {
        if (res.data.result.goods.activity_is_on == 1) {
          that.initActivity(res.data.result.goods);
        }
      }
    });
  },

  /** 减少购买的商品数量 */
  subCartNum: function (e) {
    this.checkCartNum(this.data.goodsInputNum - 1);
  },
  /** 增加购买的商品数量 */
  addCartNum: function (e) {
    this.checkCartNum(this.data.goodsInputNum + 1);
  },
  /** 输入购买的数量 */
  inputCartNum: function (e) {
    this.checkCartNum(Number(e.detail.value));
  },

  /** 检查购买的数量 */
  checkCartNum: function (num) {
    var specs = this.data.data.goods.spec_goods_price;
    var specSelect = this.data.specSelect;
    var activity = this.data.select.activity;
    var stock = this.data.data.goods.store_count;
    //参与活动
    if (activity && activity.activity_is_on == 1) {
      stock = activity.store_count
    } else {
      if (specs.length > 0) {
        stock = specs[specSelect].store_count;
      }
    }

    if (num > stock || stock == 0) {
      num = stock;
    } else if (num < 1) {
      num = 1;
    }
    this.setData({
      goodsInputNum: num
    });
  },
  /** 加入购物车 */
  addCart: function (e) {
    console.log('触发了点击事件')
    var that = this;
    var itemId = 0;
    var specs = this.data.data.goods.spec_goods_price;
    //区分有规格和无规格
    if (specs.length > 0) {
      if (specs[this.data.specSelect].store_count <= 0) {
        return app.showTextWarining("当前无库存！");
      }
      itemId = specs[this.data.specSelect].item_id;
    } else {
      if (this.data.data.goods.store_count <= 0) {
        return app.showTextWarining("当前无库存！");
      }
    }
    if (this.data.goodsInputNum <= 0) {
      return app.showTextWarining("商品数量不能小于1");
    }
    var data = {
      goods_id: this.data.data.goods.goods_id,
      goods_num: this.data.goodsInputNum,
      item_id: itemId,
      type: 2
    };
    var index=0;
    for(var i=0;i<this.data.goods.length;i++) {
      if(this.data.goods[i].goods_id == this.data.data.goods.goods_id) {
        index = i;
        break;
      }
    }
    if (this.data.data.goods.is_virtual) {
      return this.buyVirtualGoods(data);
    }
    if (e.currentTarget.dataset.action == 'add') { //加入购物车
      if (this.data.shippingCost < 0 || this.data.select.stock <= 0 || !this.data.hasSpec) {
        return;
      }
      request.post('/api/cart/add', {
        data: data,
        success: function (res) {
          that.setData({
            openSpecModal: false,
            // ['goods[' + index + '].cart_num']: that.data.goodsInputNum,
            // ['goods[' + index + '].cart_id']: res.data.cart_id
          });
          that.getGoods(that.data.subCategoryId, 1);
          request.checkUniqueId();
          app.showTextWarining('加入购物车成功');
          that.requestCardNum();
        }
      });
    } else if (e.currentTarget.dataset.action == 'exchange') { //立即兑换
      this.exchange(data);
    } else if (e.currentTarget.dataset.action == 'reserve') { //立即预订
      this.reserve(data);
    } else { //立即购买
      this.buyNow(data);
    }
  },

  /** 请求购物车数量 */
  requestCardNum: function () {
    var that = this;
    request.get('/api/cart/getCartNum?type=2', {
      isShowLoading: false,
      success: function (res) {
        that.setData({
          cartGoodsNum: res.data.result
        });
      }
    });
  },

  toOrder() {
    wx.navigateTo({
      url: '/subPages/pages/order/breakfastOrder/breakfastOrder',
    })
  },

  addNum: function (e) {
    let that = this;
    //在个人中心浏览其他入口页面前判断是否登录
    if (!that.data.userInfo) {
      app.getUserInfo(function (userInfo) {
        that.setData({
          userInfo: userInfo,
          click: false
        });
      }, true, false);
      return false;
    }
    let index = e.currentTarget.dataset.item
    let cart = that.data.goods[index];
    let data = {
      goods_id: cart.goods_id,
      goods_num: 1,
      item_id: 0,
      type: 2
    }
    request.post('/api/cart/add', {
      data: data,
      isShowLoading: false,
      success: function (res) {
        if (res.data.status == 1) {
          cart.cart_num++;
          that.setData({
            ['goods[' + index + '].cart_num']: cart.cart_num,
            ['goods[' + index + '].cart_id']: res.data.cart_id
          });
          that.requestCardNum();
        }
      }
    })
  },

  subNum(e) {
    let that = this;
    //在个人中心浏览其他入口页面前判断是否登录
    if (!that.data.userInfo) {
      app.getUserInfo(function (userInfo) {
        that.setData({
          userInfo: userInfo,
          click: false
        });
      }, true, false);
      return false;
    }
    console.log(e.currentTarget.dataset)
    console.log(this.data.goods)
    let index = e.currentTarget.dataset.item
    let cart = this.data.goods[index]
    let data = {
      'cart[id]': cart.cart_id,
      'cart[goods_num]': cart.cart_num - 1,
      type:2
    }
    request.post(that.data.url + '/api/cart/changeNum', {
      data: data,
      success: function (res) {
        if (res.data.status == 1) {
          that.setData({
            ['goods[' + index + '].cart_num']: cart.cart_num - 1
          });
          // 更新购物车角标数量
          that.AsyncUpdateCart();
        }
      },
      isShowLoading: false
    });
  },
  /** 查询购物车选中商品价格 */
	AsyncUpdateCart: function () {
		var that = this;
		// var data = that.data.requestData.cart_list;
		// var str = ""
		// for (var i = 0; i < data.length; i++) {
		// 	if (i == 0) {
		// 		str += "?cart[" + i + "][id]=" + data[i]['id']
		// 		str += "&cart[" + i + "][selected]=" + data[i]['selected']
		// 	} else {
		// 		str += "&cart[" + i + "][id]=" + data[i]['id']
		// 		str += "&cart[" + i + "][selected]=" + data[i]['selected']
		// 	}
		// }
		request.get(that.data.url + '/api/cart/AsyncUpdateCart?type=2', {
			isShowLoading: false,
			success: function (res) {
				that.requestCardNum();
			}
		});
	},
})